/**
 * (created at 2011-1-23)
 */
package qiushuo.mysqlparser.ast.expression.primary.function;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.ast.expression.primary.PrimaryExpression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public abstract class FunctionExpression extends PrimaryExpression {
    protected static List<Expression> wrapList(Expression expr) {
        List<Expression> list = new ArrayList<Expression>(1);
        list.add(expr);
        return list;
    }

    public abstract FunctionExpression constructFunction(List<Expression> arguments);

    protected final String functionName;
    protected final List<Expression> arguments;

    public FunctionExpression(String functionName, List<Expression> arguments) {
        this.functionName = functionName;
        if (arguments == null || arguments.size() <= 0) {
            this.arguments = Collections.emptyList();
        } else {
            if (arguments instanceof ArrayList) {
                this.arguments = arguments;
            } else {
                this.arguments = new ArrayList<Expression>(arguments);
            }
        }
    }

    public int getArgumentSize() {
        return arguments.size();
    }

    public Expression getArguments(int index) {
        return arguments.get(index);
    }

    public String getFunctionName() {
        return functionName;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            sb.append(functionName).append("(");
            boolean isFst = true;
            for (Expression arg : arguments) {
                if (isFst) isFst = false;
                else sb.append(", ");
                sb.append(arg.generateSql(type));
            }
            sb.append(")");
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }
}
